package icu.bughub.app.app.extension

import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.snapshotFlow

@Composable
fun LazyListState.OnBottomBeached(buffer: Int = 0, loadMore: () -> Unit) {

    require(buffer >= 0) { "buffer 必须大于等于0" }

    // 是否应该加载更多？
    val shouLoadMore = remember {
        //由另一个状态计算派生
        derivedStateOf {
            //获取最后显示的 item
            val lastVisibilityItem =
                layoutInfo.visibleItemsInfo.lastOrNull() ?: return@derivedStateOf true
            //最后显示的item是否是最后一个
            lastVisibilityItem.index == layoutInfo.totalItemsCount - 1 - buffer
        }
    }

    LaunchedEffect(shouLoadMore) {
        snapshotFlow { shouLoadMore.value }.collect {
            if (it) {
                loadMore.invoke()
            }
        }

    }

}